package com.zhuiyun.project.api.record.service.impl;


import com.zhuiyun.project.api.lottery.mapper.LotteryMapper;
import com.zhuiyun.project.api.record.entity.CommitRecord;
import com.zhuiyun.project.api.record.entity.MyRecord;
import com.zhuiyun.project.api.record.mapper.MyRecordMapper;
import com.zhuiyun.project.api.record.mapper.RecordMapper;
import com.zhuiyun.project.api.record.service.RecordService;
import com.zhuiyun.project.api.submitrecord.entity.SubmitRecord;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.ObjectUtils;
import com.zhuiyun.project.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName LotteryServiceImpl
 * @Description TODO
 * @Author 17179
 * @Date 2024/7/16 15:49
 **/
@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    RecordMapper recordMapper;
    @Autowired
    MyRecordMapper myRecordMapper;
    @Autowired
    LotteryMapper lotteryMapper;

    @Override
    public int saveRecord(CommitRecord record) {
        if(ObjectUtils.isNotEmpty(record.getId())&&record.getId()>0){// 修改
            //recordMapper.updateRecord(record);

            CommitRecord record1 = recordMapper.selectByPrimaryKey(record.getId());
            if(ObjectUtils.isNotEmpty(record1)&&record1.getDelFlag()==0){
                recordMapper.updateByPrimaryKeySelective(record);
            }else{
                String lastLotteryNo = getLastLotteryNo(record.getType());
                record.setLotteryNo(lastLotteryNo);
                record.setTime(new Date());
                record.setDelFlag(0);
                record.setId(null);
                recordMapper.insertUseGeneratedKeys(record);
            }
        }else{
            String lastLotteryNo = getLastLotteryNo(record.getType());
            record.setLotteryNo(lastLotteryNo);
            record.setTime(new Date());
            record.setDelFlag(0);
            recordMapper.insertUseGeneratedKeys(record);
        }
        return record.getId();

    }

    /**
     * 获得下次开奖的彩票期号
     * @param type
     * @return
     */
    public String getLastLotteryNo(String type){
        String lastLotteryNoInc = "0";
        String lastLotteryNo = lotteryMapper.getLastLotteryNo(type);
        if(ObjectUtils.isNotEmpty(lastLotteryNo)){
            // 最新期号要+1
            lastLotteryNoInc = String.valueOf((Integer.parseInt(lastLotteryNo)+1)) ;
        }
        return lastLotteryNoInc;
    }
    /**
     * 获取个人记录
     * @param deviceId
     * @return
     */
    @Override
    public List<CommitRecord> getRecordByDeviceId(String deviceId,String type) {
        List<CommitRecord> records =recordMapper.getRecordByDeviceId(deviceId,type);
        return records;
    }

    /**
     * 清空所有记录
     */
    @Override
    public void clearRecord() {
        recordMapper.clearRecord();
    }

    /**
     * 用户删除记录
     * @param id
     * @return
     */
    @Override
    public int deleteRecordById(Integer id,String type) {
        if(id==-1){  // 删除排序中提交的记录
            String phone = UserUtils.getUser().getPhone();
            int maxId = recordMapper.getMaxIdByPhoneAndType(type, phone);
            return  recordMapper.updateRecordDelFlag(maxId);
            //return recordMapper.deleteByPrimaryKey(maxIdByPhoneAndType);
        }else{
            return recordMapper.updateRecordDelFlag(id);
        }

    }

    /**
     * delFlag 0删除所有走势图和 结算结果页面的数据    1删除排序页面
     * @param delFlag 0代表从走势图提交的 1代表从排序中提交的  2  代表结算结果页面的胆码组等等 3 是从ai中提交
     * @return
     */
    @Override
    public int deleteRecordAll(int delFlag,String type) {
        String phone = UserUtils.getUser().getPhone();
        int i = 0;
        if(delFlag == 0){
            i = recordMapper.deleteAllByTypeAndPhone(phone,type);
        }else{
            i = recordMapper.deleteAllByDelFlagAndPhone(delFlag,phone,type);
        }
        return i;
    }
    /**
     * 获取数据交集
     * @param type
     * @param optionType
     * @param deviceId
     * @return
     */
    @Override
    public List<String> getDataIntersection(String type, String optionType,String deviceId) {
        deviceId = UserUtils.getUser().getPhone();
        if(ObjectUtils.isNotEmpty(type)&&ObjectUtils.isNotEmpty(optionType)){
            List<CommitRecord> records =  recordMapper.getDataIntersection(type,optionType,deviceId);
            List<String> list = null;
            if(ObjectUtils.isNotEmpty(records)){
                if(records.size()==1){ // 如果是一条数据直接返回
                    String[] split = records.get(0).getResult().replace("[", "").replace("]", "").replace("\"", "").split(",");
                    list =  Arrays.asList(split);
                }else{ //如果是多条数据获取交集
                    CommitRecord commitRecord = records.get(0);
                    String result = commitRecord.getResult();
                    if(ObjectUtils.isNotEmpty(result)) {
                        String[] split = result.replace("[", "").replace("]", "").replace("\"", "").split(",");
                        list = Arrays.asList(split);
                    }
                    for (int i=1;i< records.size();i++) {
                        CommitRecord commitRecord1 = records.get(i);
                        String result1 = commitRecord1.getResult();
                        if(ObjectUtils.isNotEmpty(result1)) {
                            String[] split = result1.replace("[", "").replace("]", "").replace("\"", "").split(",");
                            Set<String> set = new HashSet<>(Arrays.asList(split));
                            list = list.parallelStream().filter(set::contains).collect(Collectors.toList());
                        }
                    }
                }
            }
            return list;
        }
        return null;
    }

    /**
     * 号码统计
     * @param type
     * @param optionType
     * @param deviceId
     * @return
     */
    @Override
    public List getDataTotal(String type, String optionType, String deviceId) {
        if(ObjectUtils.isNotEmpty(type)&&ObjectUtils.isNotEmpty(optionType)){
            List<CommitRecord> records =  recordMapper.getDataIntersection(type,optionType,deviceId);
            List<String> list = null;
            if(ObjectUtils.isNotEmpty(records)){
                if(records.size()==1){ // 如果是一条数据直接返回
                    String[] split = records.get(0).getResult().replace("[", "").replace("]", "").replace("\"", "").split(",");
                    list =  Arrays.asList(split);
                }else{ //如果是多条数据获取交集
                    CommitRecord commitRecord = records.get(0);
                    String result = commitRecord.getResult();
                    if(ObjectUtils.isNotEmpty(result)) {
                        String[] split = result.replace("[", "").replace("]", "").replace("\"", "").split(",");
                        list = Arrays.asList(split);
                    }
                    for (int i=1;i< records.size();i++) {
                        CommitRecord commitRecord1 = records.get(i);
                        String result1 = commitRecord1.getResult();
                        if(ObjectUtils.isNotEmpty(result1)) {
                            String[] split = result1.replace("[", "").replace("]", "").replace("\"", "").split(",");
                            List<String> list1 = Arrays.asList(split);
                            list = Stream.concat(list.stream(), list1.stream())
                                    .collect(Collectors.toList());
                        }
                    }
                }
            }
            return list;
        }
        return null;
    }

    /**
     *
     * 新增我的个人记录
     * @param record
     * @return
     */
    @Override
    public int saveMyRecord(MyRecord record) {
        record.setCreateTime(new Date());
        return myRecordMapper.insert(record);
    }

    @Override
    public void clearMyRecord() {
        myRecordMapper.clearMyRecord();
    }

    /**
     *
     * 获取commit_record 表中的 result 字段
     * @param type
     * @return
     */
    @Override
    public CommonResult getResultDataCount(String type) {
        String lastLotteryNo = getLastLotteryNo(type);
        // 获取 result 中的数据
        List<String> list = recordMapper.getResultData(type,lastLotteryNo);
        List<String> l = new ArrayList<>();
        for (String s : list) {
            String replace = s.replace("[", "").replace("]", "").replace("\"", "");
            // 去掉值为空的
            if (replace.length() == 0) {
                continue;
            }
            l.addAll(Arrays.asList(replace.split(",")));
        }
        Map<String, Integer> frequencyMap = new HashMap<>();
        for (int i = 0; i <= 999; i++) {
            String key = String.format("%03d", i); // 格式化为三位数字
            frequencyMap.put(key,0); // 示例值可以根据需要更改
        }
        for (String item : l) {
            frequencyMap.put(item, frequencyMap.getOrDefault(item, 0) + 1);
        }
        // 使用 Java 8 的 Stream API 对 Map 按照 value 降序排序
        List<Map.Entry<String, Integer>> sortedEntries = frequencyMap.entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        // 构建结果对象
        return CommonResult.ok(sortedEntries.stream()
                .map(entry -> {
                    Map submitRecord = new HashMap();
                    submitRecord.put("result",entry.getKey());
                    submitRecord.put("count",entry.getValue());
//                    submitRecord.setResult(entry.getKey());
//                    submitRecord.setCount(entry.getValue());
                    return submitRecord;
                })
                .collect(Collectors.toList()));
    }
    /**
     *
     * 在排序类型中按照类型进行统计排序
     * @param type
     * @param optionType
     * @return
     */
    @Override
    public CommonResult getRecordBySort(String type, int optionType) {
        // 获取 result 中的数据
        String lastLotteryNo = getLastLotteryNo(type);
        List<String> list = recordMapper.getRecordBySort(type,lastLotteryNo);
        List<String> allList = new ArrayList<>();
        for (String s : list) {
            String replace = s.replace("[", "").replace("]", "").replace("\"", "");
            // 去掉值为空的
            if (replace.length() == 0) {
                continue;
            }
            allList.addAll(Arrays.asList(replace.split(",")));
        }
        allList.removeIf(String::isEmpty);
        Map<Integer, Integer> mapOne = new HashMap<>();
        Map<Integer, Integer> mapTwo = new HashMap<>();
        Map<Integer, Integer> mapThree = new HashMap<>();
        for (int i = 0; i <= 9; i++) {
            mapOne.put(i,0);
            mapTwo.put(i,0);
            mapThree.put(i,0);
        }
        Map result = null;
        List <String> optionList = new ArrayList<>();
        switch (optionType){
            case 0: // 百十个
                getCount(allList,mapOne,0);
                getCount(allList,mapTwo,1);
                getCount(allList,mapThree,2);
                result = getResult(mapOne, mapTwo, mapThree);
                break;
            case 7: // 百十个位差
                for (String l : allList) {
                    optionList.add(getDifferenceStringArray(l));
                }
                getCount(optionList,mapOne,0);
                getCount(optionList,mapTwo,1);
                getCount(optionList,mapThree,2);
                result = getResult(mapOne, mapTwo, mapThree);
                break;
            case 11: // 百十个位和
                for (String l : allList) {
                    optionList.add(getSumStringArray(l));
                }
                getCount(optionList,mapOne,0);
                getCount(optionList,mapTwo,1);
                getCount(optionList,mapThree,2);
                result = getResult(mapOne, mapTwo, mapThree);
                break;
            case 15: // 小号中号大号
//                for (String l : allList) {
//                    String arrayOrderBy = getArrayOrderBy(l);
//                    if(arrayOrderBy!=""){
//                        optionList.add(arrayOrderBy);
//                    }
//                }
                getCountMinMidMax(allList,mapOne,0);
                getCountMinMidMax(allList,mapTwo,1);
                getCountMinMidMax(allList,mapThree,2);
                result = getResult(mapOne, mapTwo, mapThree);
                break;
            case 19: // 小中大差
//                for (String l : allList) {
//                    String arrayOrderBy = getArrayOrderBy(l);
//                    if(arrayOrderBy!=""){
//                        optionList.add(getDifferenceStringArray(arrayOrderBy));
//                    }
//
//                }
                getCountMinMidMaxDiffer(allList,mapOne,0);
                getCountMinMidMaxDiffer(allList,mapTwo,1);
                getCountMinMidMaxDiffer(allList,mapThree,2);
                result = getResult(mapOne, mapTwo, mapThree);
                break;
            case 23: //小中大和
//                for (String l : allList) {
//                    String arrayOrderBy = getArrayOrderBy(l);
//                    if(arrayOrderBy!=""){
//                        optionList.add(getSumStringArray(arrayOrderBy));
//                    }
//
//                }

                getCountMinMidMaxCount(allList,mapOne,0);
                getCountMinMidMaxCount(allList,mapTwo,1);
                getCountMinMidMaxCount(allList,mapThree,2);
                result = getResult(mapOne, mapTwo, mapThree);
                break;
            case 43:
                for (String l : allList) {
                    optionList.add(getSumTail(l));
                }
                getCount(optionList,mapOne,0);
                result = getResult(mapOne, mapTwo, mapThree);
                break;

        }
        return CommonResult.ok(result);
    }


    /**
     * 和尾
     * @param num
     * @return
     */
    public String getSumTail(String num){
        String[] array = num.split("");
        Integer sum= (Integer.parseInt(array[0])+Integer.parseInt(array[1])+Integer.parseInt(array[2]))%10;
        return  sum+"";
    }
    /**
     * 小中大
     * @param array
     * @return
     */
    public String getArrayOrderBy(String array){
        //将字符串分割成三位数的数组
        String[] split = array.split("");
        String result = "";
        if(Integer.parseInt(split[0])<=Integer.parseInt(split[1])&&Integer.parseInt(split[1])<=Integer.parseInt(split[2])){
            result = array;
        }
        return result ;
    }
    /**
     * 百十各位的和
     * @param num
     * @return
     */
    public String getSumStringArray(String num){
        String[] arrayOrderBy = num.split("");
        Integer hundred=Integer.parseInt(arrayOrderBy[0]);
        Integer ten=Integer.parseInt(arrayOrderBy[1]);
        Integer piece=Integer.parseInt(arrayOrderBy[2]);
        //求百十和 十个和 百个和 大于十取余
        Integer hundredAndTen = Math.abs(hundred + ten)%10;
        Integer tenAndPiece = Math.abs(ten+piece)%10;
        Integer hundredAndPiece = Math.abs(hundred + piece)%10;
        String returnArray= ""+hundredAndTen+tenAndPiece+hundredAndPiece;
        return returnArray;
    }
    /**
     * 百十各位的差
     * @param num
     * @return
     */
    public String getDifferenceStringArray(String num){
        String[] arrayOrderBy = num.split("");
        //获取百位 十位 个位
        Integer hundred=Integer.parseInt(arrayOrderBy[0]);
        Integer ten=Integer.parseInt(arrayOrderBy[1]);
        Integer piece=Integer.parseInt(arrayOrderBy[2]);
        //求百十差 十个差 百个差 的绝对值
        Integer hundredAndTen = Math.abs(hundred - ten);
        Integer tenAndPiece = Math.abs(ten-piece);
        Integer hundredAndPiece = Math.abs(hundred - piece);
        String returnArray= ""+hundredAndTen+tenAndPiece+hundredAndPiece;
        return returnArray;
    }

    /**
     * 小中大计算
     * @param list
     * @param mapOne
     * @param index
     */
    public void getCountMinMidMax(List<String> list,Map<Integer, Integer> mapOne,int index){
        for (String item : list) {
            String[] split = item.split("");
            Arrays.sort(split);
            int num = Integer.parseInt(split[index]);
            mapOne.put(num, mapOne.getOrDefault(num, 0) + 1);
        }
    }
    /**
     * 小中大差
     * @param list
     * @param mapOne
     * @param index
     */
    public void getCountMinMidMaxDiffer(List<String> list,Map<Integer, Integer> mapOne,int index){
        for (String item : list) {
            if(ObjectUtils.isNotEmpty(item)){
                String[] split = item.split("");
                Arrays.sort(split);
                int arr [] = differ(split);
                int num = arr[index];
                mapOne.put(num, mapOne.getOrDefault(num, 0) + 1);
            }
        }
    }
    public int [] differ(String [] arr){
        // 将字符串转换为整数
        int num1 = Integer.parseInt(arr[0]);
        int num2 = Integer.parseInt(arr[1]);
        int num3 = Integer.parseInt(arr[2]);
        // 计算差值
        int diff1 = Math.abs(num1 - num2);  // 第一个数和第二个数的差
        int diff2 = Math.abs(num2 - num3);  // 第二个数和第三个数的差
        int diff3 = Math.abs(num1 - num3);  // 第一个数和第三个数的差
        // 将差值组成一个新的数组
        int[] result = {diff1, diff2, diff3};
        return result;
    }
    public int [] count(String [] arr){
        // 将字符串转换为整数
        int num1 = Integer.parseInt(arr[0]);
        int num2 = Integer.parseInt(arr[1]);
        int num3 = Integer.parseInt(arr[2]);
        // 计算和值
        int diff1 = Math.abs(num1 + num2)%10;  // 第一个数和第二个数的差
        int diff2 = Math.abs(num2 + num3)%10;  // 第二个数和第三个数的差
        int diff3 = Math.abs(num1 + num3)%10;  // 第一个数和第三个数的差
        // 将和值组成一个新的数组
        int[] result = {diff1, diff2, diff3};
        return result;
    }
    /**
     * 小中大和
     * @param list
     * @param mapOne
     * @param index
     */
    public void getCountMinMidMaxCount(List<String> list,Map<Integer, Integer> mapOne,int index){
        for (String item : list) {
            if(ObjectUtils.isNotEmpty(item)){
                String[] split = item.split("");
                Arrays.sort(split);
                int arr [] = count(split);
                int num = arr[index];
                mapOne.put(num, mapOne.getOrDefault(num, 0) + 1);
            }
        }
    }
    public void getCount(List<String> list,Map<Integer, Integer> mapOne,int index){
        for (String item : list) {
            if(ObjectUtils.isNotEmpty(item)){
                String[] split = item.split("");
                int num = Integer.parseInt(split[index]);
                mapOne.put(num, mapOne.getOrDefault(num, 0) + 1);
            }
        }
    }
    public Map getResult(Map<Integer, Integer> mapOne,Map<Integer, Integer> mapTwo,Map<Integer, Integer> mapThree){
        List<Map.Entry<Integer, Integer>> sortedEntriesOne = mapOne.entrySet()
                .stream()
                .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        List<Map.Entry<Integer, Integer>> sortedEntriesTwo = mapTwo.entrySet()
                .stream()
                .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        List<Map.Entry<Integer, Integer>> sortedEntriesThree = mapThree.entrySet()
                .stream()
                .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        List<Map> collectOne = sortedEntriesOne.stream()
                .map(entry -> {
                    Map submitRecord = new HashMap();
                    submitRecord.put("number", entry.getKey());
                    submitRecord.put("count", entry.getValue());
                    submitRecord.put("selected", true);
                    return submitRecord;
                })
                .collect(Collectors.toList());
        List<Map> collectTwo = sortedEntriesTwo.stream()
                .map(entry -> {
                    Map submitRecord = new HashMap();
                    submitRecord.put("number", entry.getKey());
                    submitRecord.put("count", entry.getValue());
                    submitRecord.put("selected", true);
                    return submitRecord;
                })
                .collect(Collectors.toList());
        List<Map> collectThree = sortedEntriesThree.stream()
                .map(entry -> {
                    Map submitRecord = new HashMap();
                    submitRecord.put("number", entry.getKey());
                    submitRecord.put("count", entry.getValue());
                    submitRecord.put("selected", true);
                    return submitRecord;
                })
                .collect(Collectors.toList());

        Map result = new HashMap();
        result.put("tablesDataOne",collectOne);
        result.put("tablesDataTwo",collectTwo);
        result.put("tablesDataThree",collectThree);
        return result;
    }
    @Override
    public CommonResult getAiRecordByType(String type,int limit) {
        List<String> sortedList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(type)) {
            List<String> allList = new ArrayList<>();
            String lastLotteryNo = getLastLotteryNo(type);
            List<String> records = recordMapper.getAiRecordByType(type,lastLotteryNo);
            for (String s : records) {
                String replace = s.replace("[", "").replace("]", "").replace("\"", "");
                // 去掉值为空的
                if (replace.length() == 0) {
                    continue;
                }
                allList.addAll(Arrays.asList(replace.split(",")));
            }
            // 统计出现次数
            Map<String, Integer> countMap = new HashMap<>();
            for (String item : allList) {
                countMap.put(item, countMap.getOrDefault(item, 0) + 1);
            }
            // 使用列表存储结果并进行排序
            List<Map.Entry<String, Integer>> entryList = new ArrayList<>(countMap.entrySet());
            // 按照出现次数降序排序
            entryList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
            // 创建一个新的列表用于存储排序后的数据
            // 将排序后的字符串按出现次数添加到新的列表中
            for (Map.Entry<String, Integer> entry : entryList) {
                sortedList.add(entry.getKey()); // 可以选择将 entry.getValue() 添加到这里，如果需要次数也存储
            }
            limit = Math.min(limit, sortedList.size());
            sortedList = sortedList.subList(0, limit);
        }
        return CommonResult.ok(sortedList);
    }


}
